import React, { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import Breadcrumb from "../components/Breadcrumb";
import Footer from "../components/Footer";
import Header from "../components/Header";
import { base, newsDetail } from "../service";
import { data } from "../util";

export default function NewsDetails() {
  const pathList = [
    { pid: 10, title: "首页", href: "/" },
    { pid: 10, title: "新闻中心", href: "/news" },
    { pid: 10, title: "新闻详情", href: "/news_details" },
  ];

  /* ------------------------------------------------------- */

  // 状态变量 => 新闻详情
  let [news, setNews] = useState({});

  /* ------------------------------------------------------- */

  // 使用钩子读取路由参数/搜索参数
  let [params] = useSearchParams();

  /* ------------------------------------------------------- */

  // 生命周期方法 => 组件挂载时
  useEffect(() => {
    (async () => {
      // 读取上个页面传递来的路由参数:新闻编号(nid)
      // console.log(params.get("nid"));
      let nid = params.get("nid");
      // 根据新闻编号查询服务器端接口,获取新闻详情
      let data = await newsDetail(nid);

      // 对服务器端返回的数据进行预处理
      // 把 src = "  替换成 src=" https://www.codeboy.com/mfresh
      data.content = data.content.replace(/src="/g, `src="${base}`);

      console.log(data);
      setNews(data);
    })();
  }, []);

  /* ------------------------------------------------------- */

  return (
    <>
      {/* F1:页头 */}
      <Header></Header>

      {/* F2:面包屑 */}
      <Breadcrumb list={pathList}></Breadcrumb>

      {/* F3:主体 */}
      <div className="main container">
        <div className="news_details">
          <h2>{news.title}</h2>
          <span>发布时间：{data(news.pubTime)}</span>
          {/* innerText 文本绑定 */}
          {/* <div className="news_content">{news.content}</div> */}

          {/* innerHTML 文本绑定 */}
          <div
            className="news_content"
            dangerouslySetInnerHTML={{ __html: news.content }}
          ></div>
        </div>
      </div>

      {/* F4:页脚 */}
      <Footer></Footer>
    </>
  );
}
